<template>
    <section>

      <el-tabs @tab-click="tabClick" tab-position="top" >
        <el-tab-pane label="员工领用审核">
          <section>
            <el-col :span="24" style="padding-top:0px;padding-bottom:10px;">
              <el-dropdown trigger="click">
                <el-button round type="primary" size="small">
                  一键审核<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native = "reviewList(0)">通过所选</el-dropdown-item>
                  <el-dropdown-item @click.native = "reviewList(1)">不通过所选</el-dropdown-item> 
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
             <el-table
                  v-loading="listLoading"
                border
                ref="multipleTable" 
                :data="assignData"
                :span-method="assetSpanMethod"
                tooltip-effect="dark"
                style="width: 100%"
                @row-click="rowClick"
                @selection-change="reviewSelectionChange">
                <el-table-column
                  type="selection">
                </el-table-column> 
                <el-table-column
                  prop="assignId"
                  label="领用编号"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="assignUserName"
                  label="领用人"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="useCompany"
                  label="领用后使用公司"
                  width="220">
                </el-table-column>
                <el-table-column
                  prop="departmentName"
                  label="领用后使用部门"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="userName"
                  label="领用后使用员工"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="assignArea"
                  label="领用后存放区域"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="storePlace"
                  label="领用后存放位置"
                  width="120">
                </el-table-column>
                <el-table-column
                min-width="120px"
                  prop="assignTime"
                  label="领用时间">
                </el-table-column>  
                <el-table-column
                  min-width="180px"
                  fixed="right"
                  prop="assignTime"
                  label="操作">
                    <template slot-scope="scope">
                      <el-button type="text" size="small">查看</el-button>
                      <el-button type="text" size="small" @click="reviewClick(2)">通过</el-button>
                      <el-button type="text" size="small" @click="reviewClick(4)">不通过</el-button>
                    </template>
                </el-table-column>
              </el-table>
              <el-col :span="24" class="toolbar">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[20, 50, 100, 200]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalNum">
                    </el-pagination>
                </el-col>
          </section>
        </el-tab-pane>
        <el-tab-pane label="领用记录">
          <section>
                    <el-col :span="24" style="padding-top:0px;padding-bottom:10px;">
                        <el-button round type="primary" @click="dialogFormVisible = true"  size="small" icon="el-icon-plus">新增领用</el-button> 
                        <!-- <el-button round size="small" type="primary" plain class="el-dropdown-link">
                                <i><font-awesome-icon :icon="['fas','sign-out-alt']"/></i>&nbsp;导出
                        </el-button> -->
                    </el-col>
                    <el-table
                  v-loading="listLoading"
                border
                ref="multipleTable" 
                :data="assignData"
                :span-method="assetSpanMethod"
                tooltip-effect="dark"
                style="width: 100%"
                @row-click="rowClick"
                @selection-change="handleSelectionChange">
                <el-table-column
                  type="selection">
                </el-table-column> 
                <el-table-column
                  prop="assignId"
                  label="领用编号"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="assignUserName"
                  label="领用人"
                  width="120">
                </el-table-column> 
                <el-table-column
                  prop="useCompany"
                  label="领用后使用公司"
                  width="220">
                </el-table-column>
                <el-table-column
                  prop="departmentName"
                  label="领用后使用部门"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="userName"
                  label="领用后使用员工"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="assignArea"
                  label="领用后存放区域"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="storePlace"
                  label="领用后存放位置"
                  width="120">
                </el-table-column>
                <el-table-column
                min-width="120px"
                  prop="assignTime"
                  label="领用时间">
                </el-table-column> 
                <el-table-column
                  min-width="80px" 
                  label="操作">
                  <template slot-scope="scope">
                      <el-button type="text" size="small">查看</el-button>
                  </template>
                </el-table-column> 
              </el-table>
              <el-col :span="24" class="toolbar">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[20, 50, 100, 200]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalNum">
                    </el-pagination>
                </el-col>
          </section>
        </el-tab-pane>
      </el-tabs>
        <el-dialog title="新增领用" :visible.sync="dialogFormVisible"  @open="dialogOpen" @close="resetForm('addForm')">
            <el-form :model="addForm" size="small" :rules="rules" label-position="right" ref="addForm" label-width="120px">
                <el-row :gutter="10">
                    <el-col :span="24">
                        <el-form-item label="使用人员" prop="radio">
                             <el-radio :disabled="showDetail" v-model="addForm.radio" label="1" @change="selectRadio">领用人自己</el-radio>
                            <el-radio :disabled="showDetail" v-model="addForm.radio" label="2" @change="selectRadio">部门</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                    <el-form-item label="领用人" prop="assignName" >
                        <el-input :disabled="showDetail" placeholder="请选择" v-model="selectItem.realName" @change="searchUserName">
                            <i slot="append" class="fa-icon-location" @click="selectUser(true)">
                                <font-awesome-icon :icon="['fa','user']"/>
                            </i>
                        </el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="8">
                    <el-form-item label="领用时间" prop="assignDate">
                         <el-date-picker
                            v-model="addForm.assignDate"
                            type="date"
                            :disabled="showDetail"
                            format="yyyy-MM-dd HH:mm:ss" 
                            value-format="yyyy-MM-dd HH:mm:ss"
                            @change="inDateChange"
                            placeholder="选择日期">
                            </el-date-picker>
                    </el-form-item>
                    </el-col>
                    
                    <el-col :span="8">
                    <el-form-item label="经办人">
                        <el-input  v-model="localUser.userName" disabled></el-input>
                    </el-form-item>
                    </el-col> 
                    <el-col :span="8">
                    <el-form-item label="使用部门" prop="department">
                         <el-cascader    
                            :options="groupTemp"
                            :disabled="showDetail?true:canSelectCompany"
                            v-model="addForm.department" 
                            @change="handleDepartmentChange"
                            :props="classifyProps">
                        </el-cascader>
                    </el-form-item>
                    </el-col>
                    <el-col :span="8">
                    <el-form-item label="领用后存放区域" prop="area">
                        <el-select :disabled="showDetail" v-model="addForm.area" filterable placeholder="请选择">
                            <el-option
                            v-for="item in areaList"
                            :key="item.id"
                            :label="item.areaName"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="8">
                    <el-form-item label="存放地点" prop="place">
                        <el-input
                                :disabled="showDetail" v-model="addForm.place"></el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="8">
                            <el-form-item label="使用期限" prop="endTime"> 
                                <el-date-picker
                                v-model="addForm.endTime"
                                type="date"
                                :disabled="showDetail"
                                @change="endDateChange"
                                format="yyyy-MM-dd" 
                                value-format="yyyy-MM-dd"
                                placeholder="使用结束日期(默认长期)"> 
                                </el-date-picker>
                            </el-form-item> 
                             </el-col>
                    <el-col :span="8">
                    <el-form-item label="备注" prop="note"> 
                        <el-input
                                type="textarea"
                                :rows="2"
                                :disabled="showDetail"
                                placeholder="请输入备注"
                                v-model="addForm.note">
                                </el-input>
                    </el-form-item>
                    </el-col>
                    
                        <el-col  v-show="!showDetail"  :span="24" style="margin-bottom:10px;">
                            <el-button round type="primary" @click="selectAsset(true)" size="small" icon="el-icon-plus">选择领用资产</el-button> 
                            <el-button round  @click="removeAsset" size="small" class="el-icon-delete"> 移 除</el-button> 
                        </el-col>
                     
                     <el-table
                        v-loading="listLoading"
                        border
                        ref="multipleTable"
                        :data="selectAssets"
                        tooltip-effect="dark"
                        style="width: 100%;"
                        @selection-change="itemSelectionChange">
                        <el-table-column
                        v-show="!showDetail"
                        type="selection">
                        </el-table-column>
                        <el-table-column 
                        prop="assetName"
                        label="名称"
                        width="120">
                        </el-table-column> 
                        <el-table-column
                        prop="assetNum"
                        label="编号"
                        width="120">
                        </el-table-column>
                        <el-table-column
                        prop="standardName"
                        label="规格">
                        </el-table-column>
                        <el-table-column
                        prop="unitPrice"
                        label="单价">
                        </el-table-column>
                        <el-table-column
                        prop="belongName"
                        label="所属公司"
                        width="120">
                        </el-table-column> 
                        <el-table-column
                        prop="inboundTime"
                        label="入库时间"
                        width="120"
                        show-overflow-tooltip>
                        </el-table-column>
                    </el-table> 
                </el-row> 
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                
                <el-button v-show="!showDetail" @click="resetForm('addForm')">重置</el-button>
                <el-button v-show="!showDetail" type="primary" @click="submitForm('addForm')">确 定</el-button>
            </div>
        </el-dialog>      

        <el-dialog title="选择使用员工" :visible.sync="isDialogShow" @close="selectUser(false)">
            <section>
                <EmployeeTable></EmployeeTable>
            </section>
            <div slot="footer" class="dialog-footer">
                <el-button @click="selectUser(false)">取 消</el-button> 
            </div>
        </el-dialog> 

         <el-dialog title="选择资产" :visible.sync="isAssetDialogShow" @open="assetOpen" @close="selectAsset(false)">
            <section>
                <AssetsTable ref="assetDialogss"></AssetsTable>
            </section>
            <div slot="footer" class="dialog-footer">
                <el-button @click="selectAsset(false)">取 消</el-button> 
                <el-button type="primary" @click="selectAsset(false)">确 定</el-button> 
            </div>
        </el-dialog>  
    </section>

</template>

<script>
import EmployeeTable from "@/views/system/employee/employees/Container";
import AssetsTable from "@/views/system/staticassets/assets/AssetsTable";
import {formatDate} from '@/common/DateUtil.js';
import api from "@/service/api";
import http from "@/service/http";
import store from "@/store";
import { mapActions, mapGetters } from "vuex";
import { Container } from "element-ui";
//const { mapActions, mapGetters } = createNamespacedHelpers("system/employee");

export default {
  components: { EmployeeTable, AssetsTable },

  data() {
    var validateAssignName = (rule, value, callback) => {
      if (this.selectItem.userName === "") {
        callback(new Error("请选择领用人"));
      } else {
        callback();
      }
    };
    return {
      localUser: {},
      dialogFormVisible: false,
      mult: [],
      selectAssignList:[],
      reviewAssignList:[],
      canSelectCompany: true,
      listLoading: false,
      departmentList: [],
      areaList: [],
      groupTemp: [],
      selectItems: [],
      listLoading: false,
      pageSize: 20,
      totalNum: 0,
      tabIndex:0,//tab的下标
      currentPage: 1,
      assignData: [],
      addForm: {
        area: "",
        place: "",
        department: [],
        assignDate: new Date(),
        endTime: "",
        tableData: [],
        radio: "1",
        note: "",
        assignName: ""
      },
      classifyProps: {
        label: "name",
        value: "id",
        children: "child",
        disabled: "disabled"
      },
      rules: {
        radio: [
          { required: true, message: "请选择使用人员", trigger: "change" }
        ],
        assignName: [
          { validator: validateAssignName, required: true, trigger: "blur" }
        ]
      },
      showDetail:false
    };
  },
  computed: {
    //导入store的getters属性
    ...mapGetters({
      isToSelect: "system/employee/isToSelect",
      isDialogShow: "system/employee/isDialogShow",
      selectItem: "system/employee/selectItem",
      selectAssets: "system/asset/selects",
      isAssetDialogShow: "system/asset/isDialogShow"
    })
  },
  methods: {
    //导入actions方法
    ...mapActions({
      toSelect: "system/employee/toSelect",
      showDialog: "system/employee/showDialog",
      selectEpmloyeeItem: "system/employee/selectEpmloyeeItem",
      assetShowDialog: "system/asset/showDialog",
      assetSelectionChange: "system/asset/handleSelectionChange",  
      assetToSelect: "system/asset/toSelect",
      searchAssets: "system/asset/searchAssets"
    }),
    rowClick(row) {   
      this.showDetail = true;
      //设置资产
      this.assetSelectionChange(row.assetInfo);
      this.dialogFormVisible = true; 
      this.addForm.area=row.assignArea;
      this.addForm.place = row.storePlace; 
      this.addForm.radio = row.userType==3?"1":"2";
      this.addForm.endTime = row.useType == 1?"":row.assetInfo[0].endDate;
      this.addForm.assignDate= row.assignTime; 
      this.addForm.department = row.departmentPids==undefined?[]:row.departmentPids;
      this.addForm.note = row.note;
      //this.user.userName = row.operatorName;
      this.selectEpmloyeeItem({
        userId: '',
        userName: row.assignUserName,
        userType: ''
      }); 
    },
    //审核列表
    reviewList(index){
      if(index <= 1){
        if(this.reviewAssignList.length==0){
          this.$alert("请选择记录");
          return;
        }else{
          this.reviewAssign(index);
        }
      }else{

      }
    },
    reviewClick(reviewType){
        console.log(reviewType)
    },
    //资产dialog open
    assetOpen(){ 
       
    },
    //根据领用id审核领用
    reviewAssign(assignList,index){
      if(index<=1){
        let reType = index==0?2:4;
        this.$confirm(index==0?'确定通过所选审核吗?':'确定拒绝所选审核吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            let ids = [];
            this.reviewAssignList.map((v, k) => {
              ids.push(v.assignId);
            });  
            http.post(api.sysApi.reviewEmployeeAssign, {assignIds:ids,reviewType:reType}).then(data => {
              if(!data.success){
                return;
              }
              this.$message({
                message: index==0?"已通过":"已拒绝",
                type: "success"
              });
              this.getAssignList();
            });
        }).catch(() => {});
      }
    },
    //提交+验证
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addAssign();
        } else {
          return false;
        }
      });
    },
    //选中item
    itemSelectionChange(vals) {
      this.mult = vals;
    },
    //移除选择的资产
    removeAsset() {
      var me = this;
      if (this.mult.length == 0) {
        this.$alert("请选择要移除资产");
        return;
      }
      let temp = [];
      let temp2 = me.selectAssets;
      let tempI = [];
      this.mult.forEach(function(item1) {
        temp2.splice(temp2.findIndex(item => item.id == item1.id), 1);
      });
      this.$refs.assetDialogss.setSelection(temp2);
    },
    //删除领用记录
    delAssign(){
      if(this.selectAssignList.length==0){
        this.$alert("请选择记录");
        return;
      }
      this.$confirm('确认删除所选领用记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = [];
                    this.selectAssignList.map((v, k) => {
                      ids.push(v.id);
                    }); 
                    http.post(api.sysApi.delAssetAssignList, ids).then(data => {
                      if(!data.success){
                        return;
                      }
                      this.$message({
                        message: "删除记录成功",
                        type: "success"
                      });
                      this.getAssignList();
                    });
                }).catch(() => {});
    },
    //领用
    addAssign() {
      var me = this;
      let param = {
        assignDate: formatDate(new Date(this.addForm.assignDate), "yyyy-MM-dd hh:mm:ss"),
        assignUserId: this.selectItem.userId,
        note: this.addForm.note,
        areaId: this.addForm.area,
        storePlcae: this.addForm.place,
        userInfos: []
      }; 
      this.selectAssets.forEach(function(item) {
        let useItem = {
          userId:
            me.addForm.radio == "1"
              ? me.selectItem.userId
              : me.addForm.department[me.addForm.department.length - 1],
          userType: me.addForm.radio == "1" ? 3 : 2,
          assetId: item.id,
          useType: me.addForm.endTime == "" ? 1 : 2,
          endDate: formatDate(new Date(me.addForm.endTime), "yyyy-MM-dd hh:mm:ss")
        };
        param.userInfos.push(useItem);
      });
      http.post(api.sysApi.assignAsset, param).then(data => {
        if(!data.success){
          return;
        }
        this.$message({
          message: "领用成功",
          type: "success"
        });
        this.dialogFormVisible = false;
        this.getAssignList();
      });
    },
    tabClick(tab){
        this.tabIndex = tab.index;
        this.getAssignList();
    },
    //搜索是否存在用户
    searchUserName(val) {},
    //选择部门
    handleDepartmentChange(val) {
      if (val.length == 0) {
        return;
      }
      this.addForm.department = val;
    },
    inDateChange(val) {
      this.addForm.assignDate = val;
      console.log(val);
    },
    endDateChange(val) {
      this.addForm.endTime = val; 
    },
    //使用对象radio
    selectRadio(val) {
      if (!this.canSelectCompany) {
        this.department = [];
      }
      this.canSelectCompany = val == "1" ? true : false;
    },
    //选择领用人员
    selectUser(val) {
      if(this.showDetail){
        return;
      }
      this.showDialog(val);
      this.toSelect(val);
    },
    //选择资产
    selectAsset(val) {
      this.assetShowDialog(val);
    },
    //获取组织架构
    getDepartmentList() {
      http.post(api.sysApi.getDepartmentList, "").then(data => {
        if(!data.success){
				return;
			}
        this.departmentList = data.data;
        this.groupTemp = data.data;
      });
    },
    //获取区域
    getAreaList() {
      let param = { pageNum: 1, pageSize: 200 };
      http.post(api.sysApi.getAreaList, param).then(data => {
        if(!data.success){
				return;
			}
        this.areaList = data.data;
      });
    },
    //dialog open
    dialogOpen() {  
      this.getDepartmentList();
      if(this.showDetail){
        return;
      }else{
        this.user = JSON.parse(localStorage.getItem("user"));
      }
      this.areaList = []; 
      this.addForm.radio="1";
      this.addForm.assignDate=new Date();
      this.showDetail = false;
      this.getAreaList();
      this.assetToSelect(true);
      this.assetSelectionChange([]);
      this.searchAssets();
    },
    //重置
    resetForm(formName) {
      this.showDetail = false;
      this.addForm = {};
      this.$refs[formName].resetFields();
      this.selectEpmloyeeItem({
        userId: "",
        userName: "",
        userType: ""
      });
      this.assetSelectionChange([]);
      this.assetToSelect(false);
    },
    //领用列表
    getAssignList() {
      var that  = this;
      var search = { pageNum: this.currentPage, pageSize: this.pageSize,status:this.tabIndex==0?3:2 };
      http.post(api.sysApi.selectAssetAssignList, search).then(data => {
        if(!data.success){
				return;
			}
        this.assignData = data.data;
        this.totalNum = data.totalNum;
        this.listLoading = false;
      });
    },
    //领用列表--资产列表格式化
    assetSpanMethod({ row, column, rowIndex, columnIndex }){
        console.log(row.assetInfo);

    },
    //已领用单多选
    handleSelectionChange(val) {
       this.selectAssignList = val;
    },
     //审核领用单多选
    reviewSelectionChange(val) {
       this.reviewAssignList = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAssignList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAssignList();
    }
  },
  mounted() {
    this.localUser = JSON.parse(localStorage.getItem("user"));
    this.getAssignList();
  }
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
}
.el-dialog {
  width: 80%;
}
</style>

